import { useCallback, useEffect, useRef, useState } from "react";
import { LaneMonitoringBox, NeirongBox } from "./style";
import dayjs from "dayjs";
import InfoModule from "./components/InfoModule";
import SuccessModule from "./components/SuccessModule";
import { wsIp } from "../../api/http";
import { message, Select } from "antd";
import { WebRtcStreamerxiaoxujs } from "../../assets/fun/webrtcstreamer";
import { useLocation } from "react-router-dom";
import { ISelectList } from "../../type/antd";

const ZhuangcheDaping = () => {
  const xingqi = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
    "无",
  ];
  const [xingqiValue, setXingqiValue] = useState<number>(0); //星期
  const [riqiValue, setRiqiValue] = useState<string>(); //日期
  const [timeValue, setTime] = useState<string>(); // 时间
  const ws = useRef<WebSocket | null>(null); //ws连接
  const [chepaiValue, setChepaiValue] = useState<string>(""); //车牌号
  const [pizhongValue, setPizhongValue] = useState<string>(""); //皮重
  // const [maozhongValue, setMaozhongValue] = useState<string>(''); //毛重
  const [yindaoxinxiValue, setYindaoxinxiValue] = useState<string>(""); //引导信息//前进 后退 停车 装车完成
  // const [wsStatus, setWsStatus] = useState(false);
  const [yuzhuangliang, setYuzhuangliang] = useState("");
  const [shipinList, setShipinList] = useState<ISelectList[]>([]); // 视频列表
  const [shipinUrl, setShipinUrl] = useState<string>(''); // 显示的视频地址

  const videoEle = useRef(null);
  const videoEleAdd = useRef<any>();
  const wsStatus = useRef(false);
  const location = useLocation();

  //建立ws连接
  const wsFun = useCallback(() => {
    let channelNo = location.state.channelNo;
    let url = wsIp + `/websocket/guide?channelNo=${channelNo}`;
    let reconnectInterval = 1000; // 重连间隔时间，单位毫秒
    let maxReconnectAttempts = 5; // 最大重连次数
    let reconnectAttempts = 0;
    if (channelNo) {
      ws.current = new WebSocket(url);
      ws.current.onopen = (e) => {
        wsStatus.current = true;
        reconnectAttempts = 0;
        // setWsStatus(true);
      };
      ws.current.onmessage = (e) => {
        let wsData = JSON.parse(e.data);
        console.log(wsData);
        if (wsData["A00"]) {
          //收到车牌号的信息
          setChepaiValue(wsData["A00"]);
        }
        if (wsData["A01"]) {
          //收到引导信息的消息
          setYindaoxinxiValue(wsData["A01"]);
        }
        if (wsData["A02"]) {
          //收到毛重的信息
          setPizhongValue(wsData["A02"]);
        }
        if (wsData["A66"]) {
          //收到有重的信息
          setYuzhuangliang(wsData["A66"]);
        }
        // if (wsData['A03']){
        //     //收到引导信息的信息
        //     setMaozhongValue(wsData['A03']);
        // }
      };
      ws.current.onclose = () => {
        message.error("ws连接断开");
        if (reconnectAttempts < maxReconnectAttempts) {
          setTimeout(() => {
            console.log('Attempting to reconnect...');
            reconnectAttempts++;
            ws.current = new WebSocket(url); // 重新创建 WebSocket 实例
          }, reconnectInterval);
        } else {
          console.log('Maximum reconnection attempts reached.');
        }
      };
    }
  }, [location.state.channelNo]);
  useEffect(() => {

    const videoUrl = location.state.rtspvalue;
    console.log(123);
    let arr: string[] = videoUrl.split(',')
    setShipinList(arr.map((item: string) => ({
      value: item,
      label: item
    })))
    setShipinUrl(arr[0]);
  }, [location.state.rtspvalue])
  useEffect(() => {

    let shuaxin = setInterval(() => {
      window.location.reload();
    }, 1000 * 60 * 60);
    return () => {
      clearInterval(shuaxin);
    }
  }, [])



  // 右上角回显
  const rightTopBackData = useCallback(async () => {

    if (shipinUrl) {
      if (videoEle.current) {
        if (videoEleAdd.current) {
          videoEleAdd.current.disconnect();
        }

        videoEleAdd.current = new WebRtcStreamerxiaoxujs(
          videoEle.current!,
          "http://localhost:8001"
        );
        videoEleAdd.current.connect(shipinUrl);
      }
    }
  }, [shipinUrl]);

  useEffect(() => {
    rightTopBackData();
    return () => {
      if (videoEleAdd.current) {
        videoEleAdd.current.disconnect();
      }
    };
  }, [rightTopBackData]);
  // function beforeunload(e: any) {
  //   if (videoEleAdd.current) {
  //     videoEleAdd.current.disconnect();
  //   }
  //   let confirmationMessage = "你确定离开此页面吗?";
  //   (e || window.event).returnValue = confirmationMessage;
  //   return confirmationMessage;
  // }
  useEffect(() => {
    return () => {
      // window.removeEventListener("beforeunload", beforeunload);
      // 这里写离开页面的后续操作
      // 项目中这个页面使用了websocket。所以在页面离开的时候，需要将websocket关闭掉
      // 关闭websocket
      // ws.close()
    };
  }, []);
  useEffect(() => {
    // 拦截判断是否离开当前页面
    // window.addEventListener("beforeunload", beforeunload);
  }, []);

  useEffect(() => {
    const timer = setInterval(() => {
      setTime(dayjs().format("HH:mm"));
      setXingqiValue(dayjs().day());
      setRiqiValue(dayjs().format("YYYY年MM月DD日"));
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);
  useEffect(() => {
    sizeFun();
    window.addEventListener("resize", sizeFun);
  }, []);
  useEffect(() => {
    wsFun();
  }, [wsFun]);

  const sizeFun = () => {
    let designSize = 1920;
    let html = document.getElementById("quanping");
    if (html) {
      let clientW = html.clientWidth;
      let htmlRem = (clientW * 10) / designSize;
      html.style.fontSize = htmlRem + "px";
    }
  };

  const tishiHtml = (value: string) => {
    if (value === "装车完成") {
      return <SuccessModule text="装车完成" />;
    } else {
      return (
        <InfoModule text={yindaoxinxiValue === "" ? "--" : yindaoxinxiValue} />
      );
    }
  };
  return (
    <LaneMonitoringBox id="quanping">
      <div className="header_box">
        <div className="header_left">
          <div className="log_image">
            <span>骆驼山洗煤厂智能无人装车系统</span>
          </div>
          <div className="handler_left_gun"></div>
          <div className="chedao">当前{location?.state.channelNo}号车道</div>
        </div>
        <div className="header_right">
          <div className="riqi">
            <div className="riqi_top">
              <span> {xingqi[xingqiValue]}</span>
            </div>
            <div className="riqi_bottom">
              <span> {riqiValue}</span>
            </div>
          </div>
          <div className="xiaoshi">{timeValue}</div>
        </div>
      </div>
      <NeirongBox>
        <div className="shipin_box">
          <Select
            style={{ width: '20rem', position: 'absolute', top: '0rem', right: '0rem', zIndex: '999' }}
            options={shipinList}
            value={shipinUrl}
            onChange={(value) => setShipinUrl(value)}
          />
          <video
            ref={videoEle}
            id="ZCvideo"
            controls
            muted
            preload="auto"
          ></video>
        </div>
        <div className="shuju_box">
          <div className="chepaihao">
            <span>{chepaiValue === "" ? "--" : chepaiValue}</span>
          </div>
          <div className="zhongliang_box_box">
            <div className="pizhong_box">
              <span className="pizhong_xiao"> 预装量(吨)</span>
              <span className="pizhong_da">{yuzhuangliang === "" ? "--" : yuzhuangliang}</span>
            </div>
            <div className="pizhong_box">
              <span className="pizhong_xiao"> 实时量(吨)</span>
              <span className="pizhong_da">{pizhongValue === "" ? "--" : pizhongValue}</span>
            </div>
          </div>
          <div className="tishi_box">
            <span>装车中，按提示操作</span>
          </div>
          {tishiHtml(yindaoxinxiValue)}
        </div>
      </NeirongBox>
    </LaneMonitoringBox>
  );
};

export default ZhuangcheDaping;
